/* Copyright (c) 2009-2010, Sean A.O. Harney <sharney3@gmail.com> */

#include "omf.h"

/* prototypes */
void _printtime(void);
extern int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y);	/* not in omf.h */


void atexit_init(void)
{
//register _printtime() to be called at exit.
    if (atexit(_printtime) < 0)
	perror("atexit()");	// not a fatal error
}

void _printtime(void)
{

    /* NOTE: atexit() is inherited by children process up until exec()
     *  is called.
     *  Since target dl does not use exec(), this is needed here to ensure
     *  only original omf process prints */
    if (getpid() != glob.omf_pid)
	return;

//kill(regldg_pid, SIGKILL);// might already be dead.

    struct rusage ru, ru1;

    if (getrusage(RUSAGE_SELF, &ru) < 0)
      {
	  perror("getrusage()");
	  return;
      }

    if (getrusage(RUSAGE_CHILDREN, &ru1) < 0)
      {
	  perror("getrusage()");
	  return;
      }

    struct timeval endtime, realtime;
    if (gettimeofday(&endtime, NULL) < 0)
      {
	  perror("gettimeofday()");
	  return;
      }
    timeval_subtract(&realtime, &endtime, &(glob.omf_starttime));

    printf("OMF process\n");
    printf("\treal time:\t%ld.%.3ld s\n", realtime.tv_sec,
	   realtime.tv_usec);
    printf("\tuser time:\t%ld.%.3ld s\n", ru.ru_utime.tv_sec,
	   ru.ru_utime.tv_usec);
    printf("\tsys time:\t%ld.%.3ld s\n", ru.ru_stime.tv_sec,
	   ru.ru_stime.tv_usec);

    printf("Descendant processes\n");
    printf("\tuser time:\t%ld.%.4ld s\n", ru1.ru_utime.tv_sec,
	   ru1.ru_utime.tv_usec);
    printf("\tsys time:\t%ld.%.4ld s\n", ru1.ru_stime.tv_sec,
	   ru1.ru_stime.tv_usec);



}
